package mil.af.amc.adpetracker.dao.hibernate;

import mil.af.amc.adpetracker.dao.EquipmentTypeDao;
import mil.af.amc.adpetracker.model.EquipmentType;
import mil.af.amc.adpetracker.model.ItemModel;
import mil.af.amc.adpetracker.model.Manufacturer;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.stereotype.Service;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * Hibernate EquipmentType DAO implementation
 *
 * @author TSgt Jason Ferguson
 */
@Service("equipmentTypeDao")
public class HibernateEquipmentTypeDao extends HibernateGenericDao<EquipmentType> implements EquipmentTypeDao {

    public HibernateEquipmentTypeDao() {
        super(EquipmentType.class);
    }

    @Deprecated
    public EquipmentType getByDescription(final String description) {

        return (EquipmentType) getHibernateTemplate().execute(new HibernateCallback() {
            public Object doInHibernate(Session session) throws HibernateException, SQLException {

                Criteria crit = session.createCriteria(EquipmentType.class);
                crit.add(Restrictions.eq("description", description.toUpperCase()));
                return crit.uniqueResult();

            }
        });
    }

    @SuppressWarnings({"unchecked"})
    public List<EquipmentType> getByManufacturer(Manufacturer manu) {

        DetachedCriteria crit = DetachedCriteria.forClass(ItemModel.class);
        DetachedCriteria subcrit = crit.createCriteria("manufacturer");
        subcrit.add(Restrictions.eq("id", manu.getId()));

        List<ItemModel> modelList = getHibernateTemplate().findByCriteria(crit);
        List<EquipmentType> results = new ArrayList<EquipmentType>();
        for (Iterator<ItemModel> it=modelList.iterator(); it.hasNext();) {
            ItemModel nextModel = it.next();
            if (!results.contains(nextModel.getType())) {
                results.add(nextModel.getType());
            }
        }

        return results;
    }

}
